
#include "WebsocketManger.h"
#include "Upgrader.h"
#include "../../http/Request.h"
#include "../../http/httpserver/ResponseWriter.h"
#include "../../loop/LoopService.h"
#include <functional>
#include <assert.h>

std::error_code WebsocketManger::upgrade(std::shared_ptr<Request> r, 
    std::shared_ptr<ResponseWriter> rw)
{
    Upgrader g(r, rw);
    std::error_code ec;
    auto conn = g.upgrade(ec);
    if (ec) {
        rw->write(HTTPStatus::StatusBadRequest, "upgrade error");
        return ec;
    }
    conn->set_message_handle(message_fun_);
    using namespace std::placeholders;
    conn->set_close_handle(std::bind(&WebsocketManger::close_handle, this, _1, _2));
    con_set_.insert(conn);
    if (open_fun_) {
        open_fun_(conn);
    }
    return std::error_code();
}

void WebsocketManger::close_handle(const WebsocketConnPtr& conn, const std::error_code& e)
{
    if (close_fun_) {
        close_fun_(conn, e);
    }
    conn->shutdown();
    con_set_.erase(conn);
}
